﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;

namespace Wp7Tools.Services {
	public class DataStorage {

		private static object _sync = new object();

		public byte[] Load(string file) {
			lock (_sync) {
				using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) {
					using (IsolatedStorageFileStream stream = storage.OpenFile(file, FileMode.Open)) {
						byte[] buffer = new byte[stream.Length];
						stream.Read(buffer, 0, (int) stream.Length);
						return buffer;
					}
				}
			}
		}

		public void Save(string file, byte[] bytes) {
			lock (_sync) {
				using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) {
					using (IsolatedStorageFileStream stream = storage.OpenFile(file, FileMode.Create)) {
						using (BinaryWriter writer = new BinaryWriter(stream)) {
							writer.Write(bytes);
						}
					}
				}
			}
		}

		public string[] List(string path) {
			return List(path, "*");
		}

		public string[] List(string path, string searchPattern) {
			lock (_sync) {
				using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) {
					List<string> files = storage.GetFileNames(Path.Combine(path, searchPattern)).ToList();
					return files.Select(x => Path.Combine(path, x)).ToArray();
				}
			}
		}

		public string GetOldestFile(string directoryPath) {
			lock (_sync) {
				using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) {
					var files = List(directoryPath);
					if(files.Length == 0) {
						return null;
					}
					int oldestFile = 0;
					DateTime oldest = DateTime.Now;
					for (int i = 0; i < files.Length; i++) {
						DateTime date = storage.GetLastAccessTime(files[i]).LocalDateTime;
						if(oldest > date) {
							oldest = date;
							oldestFile = i;
						}
					}
					return files[oldestFile];
				}
			}
		}

		public bool Delete(string file) {
			lock (_sync) {
				using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) {
					if (storage.FileExists(file)) {
						storage.DeleteFile(file);
						return true;
					}
					return false;
				}
			}
		}

		public void CreateDirectory(string path) {
			lock (_sync) {
				using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) {
					if (!storage.DirectoryExists(path)) {
						storage.CreateDirectory(path);
					}
				}
			}
		}

		public bool Exists(string file) {
			lock (_sync) {
				using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) {
					return storage.FileExists(file);
				}
			}
		}
	}
}